package com.spider.weixin.handler;

import com.spider.model.WxFansDO;
import com.spider.service.WxFansService;
import com.spider.weixin.WeixinService;
import com.spider.weixin.builder.TextBuilder;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.ArrayUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *
 * @author Binary Wang
 *
 */
@Component
public class SubscribeHandler extends AbstractHandler{

  @Autowired
  private WxFansService wxFansService;

  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                  WxSessionManager sessionManager) throws WxErrorException {

    this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

    WeixinService weixinService = (WeixinService) wxMpService;

    // 获取微信用户基本信息
    WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);

    if (userWxInfo != null) {
      // TODO 可以添加关注用户到本地
      WxFansDO wxFansDO = new WxFansDO();
      wxFansDO.setSubscribe(userWxInfo.getSubscribe());
      wxFansDO.setOpenid(userWxInfo.getOpenId());
      wxFansDO.setNickname(userWxInfo.getNickname());
      //wxFansDO.setSex(userWxInfo.getSexId());
     // wxFansDO.setProvince(userWxInfo.getProvince());
     // wxFansDO.setCountry(userWxInfo.getCountry());
      //wxFansDO.setCity(userWxInfo.get());
      wxFansDO.setLanguage(userWxInfo.getLanguage());
      wxFansDO.setHeadimgurl(userWxInfo.getHeadImgUrl());
      wxFansDO.setSubscribeTime(DateUtil.date(userWxInfo.getSubscribeTime()*1000));
      wxFansDO.setRemark(userWxInfo.getRemark());
      wxFansDO.setGroupid(userWxInfo.getGroupId());
      wxFansDO.setTagidList(ArrayUtil.join(userWxInfo.getTagIds(),","));
      wxFansService.save(wxFansDO);
    }

    WxMpXmlOutMessage responseResult = null;
    try {
      responseResult = handleSpecial(wxMessage);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    if (responseResult != null) {
      return responseResult;
    }

    try {
      return new TextBuilder().build("主人，终于等到您来了！我是小影，发送您想看的电影名称，就能得到下载地址啦~~", wxMessage, weixinService);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    return null;
  }

  /**
   * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
   */
  protected  WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
    return null;
  }

}
